<script lang="tsx" setup>
import { NButton, NPopconfirm, NSwitch, NTooltip } from 'naive-ui';
import { toRefs } from 'vue';
import { asyncTenantPakcage, changeStatus, delTenant, getPageList } from '@/service/api/tenants/tenant';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAppStore } from '@/store/modules/app';
import { $t } from '@/locales';
import { useDict } from '@/utils/dict';
import type { TenantVO } from '@/service/types/tenant';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { useBoolean } from '~/packages/hooks/src';
import TenantSearch from './components/tenant-search.vue';
import AddTenantStepsForm from './components/add-tenant-steps-form.vue';
import EditTenantForm from './components/edit-tenant-form.vue';
const { sys_normal_disable } = toRefs<any>(useDict('sys_normal_disable'));
const appStore = useAppStore();
const { bool: show, setTrue: openShow } = useBoolean();

const requestRemove = async (id: number | number[]): Promise<boolean> => {
  const loadinginstance = (window as any).$message.loading('正在处理中');
  const { data, error } = await delTenant(id);
  loadinginstance.destroy();
  if (!error) {
    (window as any).$message.success(data?.msg);
    return Promise.resolve(true);
  }
  throw new Error('false');
};
const handleDelete = async (id: number) => {
  const result = await requestRemove(id as number);
  if (result) {
    onDeleted();
  }
};
// 套餐同步
const handleSyncPackage = (id: number, packageId: number) => {
  (window as any).$dialog.warning({
    title: '警告',
    content: '你确定同步租户套餐',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { data, error } = await asyncTenantPakcage({ tenantId: id, packageId });
      if (!error) {
        (window as any).$message.success(data?.msg);
      }
    },
    onNegativeClick: () => {
      (window as any).$message.info('删除已取消');
    }
  });
};
const handleChangeStatus = (id: number, tenantId: string, status: string, companyName: string) => {
  (window as any).$dialog.warning({
    title: '警告',
    content: `确认要"停用""${companyName}"租户吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const { data, error } = await changeStatus({ id, tenantId, status });
      if (!error) {
        (window as any).$message.success(data?.msg);
      }
    },
    onNegativeClick: () => {
      (window as any).$message.info('已取消');
    }
  });
};
const { columns, columnChecks, data, getData, loading, mobilePagination, searchParams, resetSearchParams } = useTable({
  apiFn: getPageList,
  showTotal: true,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    tenantId: '',
    contactUserName: '',
    contactPhone: '',
    companyName: '',
    status: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'tenantId',
      title: '租户编号',
      align: 'center',
      minWidth: 100
    },

    {
      key: 'companyName',
      title: '企业名称',
      align: 'center',
      minWidth: 100,
      fixed: 'left',
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'contactUserName',
      title: '联系人',
      align: 'center',
      minWidth: 100
    },
    {
      key: 'contactPhone',
      title: '联系电话',
      align: 'center',
      minWidth: 100
    },

    {
      key: 'intro',
      title: '简介',
      align: 'center',
      minWidth: 100,
      ellipsis: {
        tooltip: {
          // @ts-expect-error ignore 忽略错误样式错误
          style: { maxWidth: '300px' }
        }
      }
    },
    {
      key: 'licenseNumber',
      title: '社会统一信用代码',
      align: 'center',
      minWidth: 200,
      ellipsis: {
        tooltip: {
          // @ts-expect-error ignore 忽略错误样式错误
          style: { maxWidth: '300px' }
        },
        arrowPintToCenter: true
      }
    },

    {
      key: 'expireTime',
      title: '过期时间',
      align: 'left',
      minWidth: 120,
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'address',
      title: '地址',
      align: 'center',
      minWidth: 100,
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'status',
      title: '状态',
      align: 'center',
      minWidth: 100,
      render: row => {
        let checked = false;
        const currentDict = sys_normal_disable.value.filter((item: { value: string }) => item?.value === row?.status);
        if (currentDict[0].value === '0') {
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          checked = true;
        }
        return (
          <NSwitch
            default-value={checked}
            disabled={row.tenantId === '000000'}
            on-update:value={(value: boolean) => {
              const status = value ? '0' : '1';
              handleChangeStatus(row?.id as number, row.tenantId as string, status, row.companyName as string);
            }}
            size="medium"
            v-slots={{
              checked: () => <div>启用</div>,
              unchecked: () => <div>禁用</div>
            }}
          />
        );
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      width: 200,
      render: (row: TenantVO) => (
        <div class="flex-center gap-15px">
          <NTooltip trigger="hover">
            {{
              default: () => '修改租户',
              trigger: () => (
                <NButton
                  tag="a"
                  type="primary"
                  text
                  size="small"
                  onClick={() => {
                    handleEditor(row.id);
                  }}
                >
                  {{
                    icon: () => <SvgIcon icon="ant-design:edit-outlined" />
                  }}
                </NButton>
              )
            }}
          </NTooltip>
          {row?.tenantId !== '000000' && (
            <NTooltip trigger="hover">
              {{
                default: () => '套餐同步',
                trigger: () => (
                  <NButton
                    tag="a"
                    type="primary"
                    text
                    size="small"
                    onClick={() => {
                      handleSyncPackage(row.tenantId as number, row?.packageId as number);
                    }}
                  >
                    {{
                      icon: () => <SvgIcon icon="system-uicons:refresh-alt" />
                    }}
                  </NButton>
                )
              }}
            </NTooltip>
          )}

          {row?.tenantId !== '000000' && (
            <NPopconfirm
              onPositiveClick={() => {
                handleDelete(row.id as number);
              }}
              onNegativeClick={() => {
                (window as any).$message.info('已取消删除');
              }}
            >
              {{
                default: () => $t('common.confirmDelete'),
                trigger: () => (
                  <NTooltip trigger="hover">
                    {{
                      default: () => '删除租户',
                      trigger: () => (
                        <NButton text tag="a" type="error" ghost size="small">
                          {{
                            icon: () => <SvgIcon icon="ant-design:delete-outlined" />
                          }}
                        </NButton>
                      )
                    }}
                  </NTooltip>
                )
              }}
            </NPopconfirm>
          )}
        </div>
      )
    }
  ]
});
const {
  drawerVisible,
  handleAdd,
  currentId,
  setCurrentId,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);
const handleBatchDelete = async () => {
  (window as any).$dialog.warning({
    title: '警告',
    content: '你确定删除这些吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const result = await requestRemove(checkedRowKeys.value as unknown as number[]);
      if (result) {
        onBatchDeleted();
      }
    },
    onNegativeClick: () => {
      (window as any).$message.info('删除已取消');
    }
  });
};
const handleEditor = (id: number | string) => {
  setCurrentId(id);
  openShow();
};
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <TenantSearch
      v-model:model="searchParams"
      :status="sys_normal_disable"
      @reset="resetSearchParams"
      @search="getData"
    />
    <NCard title="租户列表" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @refresh="getData"
          @delete="handleBatchDelete"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="1500"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="mobilePagination"
        class="sm:h-full"
      >
        <template #empty>
          <Empty />
        </template>
      </NDataTable>
    </NCard>

    <AddTenantStepsForm v-model:visible="drawerVisible" @submitted="getData" />
    <EditTenantForm v-model:visible="show" :current-id="currentId" @submitted="getData" />
  </div>
</template>

<style scoped></style>
